﻿using System.Text.Json;

namespace ConsoleWeatherApp
{

    internal partial class Program
    {
        private static readonly string configPath = "setting.json";
        private static AppSetting setting;

        private static readonly HttpClient client = new HttpClient();

        static async Task Main(string[] args)
        {
            await LoadConfig();
            await GetWeather();

        }



        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <returns></returns>
        static async Task LoadConfig()
        {
            try
            {
                if (File.Exists(configPath))
                {
                    var json = await File.ReadAllTextAsync(configPath);

                    // 忽略大小写
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true // 忽略大小写
                    };

                    setting = JsonSerializer.Deserialize<AppSetting>(json, options) ?? new AppSetting();
                }
                else
                {
                    Console.WriteLine("File not found");
                    Environment.Exit(1);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"配置文件错误: {ex.Message}");
                Environment.Exit(1);
            }

        }



        /// <summary>
        /// 获取天气
        /// </summary>
        /// <returns></returns>
        static async Task GetWeather()
        {
            try
            {
                var url = $"https://restapi.amap.com/v3/weather/weatherInfo?city={setting.CityCode}&key={setting.ApiKey}";
                var response = await client.GetStringAsync(url);

                // 忽略大小写
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true // 忽略大小写
                };

                var weatherData = JsonSerializer.Deserialize<WeatherResponse>(response, options);


                if (weatherData == null)
                {
                    Console.WriteLine("获取天气失败");
                    return;
                }

                if (weatherData.Status == "1")
                {
                    var live = weatherData.Lives[0];

                    Console.Clear();
                    DisplayWeatherWithAscii(live);
                    /*Console.WriteLine($"城市: {live.Province} {live.City}");
                    Console.WriteLine($"天气: {live.Weather}");
                    Console.WriteLine($"温度: {live.Temperature}℃");
                    Console.WriteLine($"湿度: {live.Humidity}%");
                    Console.WriteLine($"风向: {live.WindDirection}风");
                    Console.WriteLine($"风力: {live.WindPower}级");
                    Console.WriteLine($"更新时间: {live.ReportTime}\n");*/
                }
                else
                {
                    Console.WriteLine($"获取天气失败: {weatherData.Info}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取天气时出错: {ex.Message}");
            }
        }



        static void DisplayWeatherWithAscii(Live data)
        {
            Console.ResetColor();
            string border = "================================================";

            // 显示天气图标（带颜色）
            Console.WriteLine("\n" + border);
            var (asciiArt, color) = GetWeatherAsciiWithColor(data.Weather);
            Console.ForegroundColor = color;
            Console.WriteLine(asciiArt);
            Console.ResetColor();
            Console.WriteLine(border + "\n");

            // 温度颜色（根据温度值变化）
            Console.Write("温度: ");
            SetTemperatureColor(int.Parse(data.Temperature));
            Console.WriteLine($"{data.Temperature}℃");
            Console.ResetColor();
            Console.WriteLine(GenerateThermometer(int.Parse(data.Temperature)));

            // 湿度颜色（根据湿度值变化）
            Console.Write("\n湿度: ");
            SetHumidityColor(int.Parse(data.Humidity));
            Console.WriteLine($"{data.Humidity}%");
            Console.ResetColor();
            Console.WriteLine(GenerateHumidityBar(int.Parse(data.Humidity)));

            // 详细信息（带颜色强调）
            Console.WriteLine("\n" + border);
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"城市\t{data.Province} {data.City}");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine($"风向\t{data.WindDirection}风 {data.WindPower}级");
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine($"更新\t{data.ReportTime}");
            Console.ResetColor();
            Console.WriteLine(border);
        }


        static (string art, ConsoleColor color) GetWeatherAsciiWithColor(string weather)
        {
            var artCollection = new Dictionary<string, (string art, ConsoleColor color)>
            {
                // 晴天组 - 黄色
                ["晴"] = (SunnyArt, ConsoleColor.Yellow),

                // 多云/阴天 - 白色
                ["多云"] = (CloudyArt, ConsoleColor.White),

                // 风系 - 青色
                ["风"] = (WindArt + "风力强度：" + weather, ConsoleColor.Cyan),

                // 降雨 - 蓝色
                ["雨"] = (RainArt, ConsoleColor.Blue),

                // 雷暴 - 黄色闪烁
                ["雷"] = (ThunderArt, ConsoleColor.Yellow),

                // 雪 - 白色
                ["雪"] = (SnowArt, ConsoleColor.White),

                // 冻雨/冰雹 - 亮蓝色
                ["冻"] = (FreezingRainArt, ConsoleColor.Blue),

                // 沙尘 - 棕色
                ["尘"] = (DustArt, ConsoleColor.DarkYellow),

                // 雾霾 - 灰色
                ["雾"] = (HazeArt, ConsoleColor.Gray),

                // 极端天气 - 红色闪烁
                ["极端"] = (ExtremeArt, ConsoleColor.Red),

                // 温度提示 - 红/蓝
                ["温"] = weather.Contains("热")
                    ? (HeatArt, ConsoleColor.Red)
                    : (ColdArt, ConsoleColor.Blue),

                ["未知"] = (UnknownArt, ConsoleColor.Magenta)
            };

            var weatherType = ClassifyWeather(weather);
            return artCollection[weatherType];
        }


        /// <summary>
        /// 分类天气
        /// </summary>
        /// <param name="weather"></param>
        /// <returns></returns>
        static string ClassifyWeather(string weather)
        {
            return weather switch
            {
                string w when w.Contains("龙卷风") || w.Contains("飓风") => "极端",
                string w when w.Contains("雷") => "雷",
                string w when w.Contains("冰雹") || w.Contains("冻雨") => "冻",
                string w when w.Contains("沙尘") || w.Contains("浮尘") => "尘",
                string w when w.Contains("雾") => "雾",
                string w when w.Contains("霾") => "雾",
                string w when w.Contains("雪") => "雪",
                string w when w.Contains("雨") => "雨",
                string w when w.Contains("风") || w.Contains("清风") || w.Contains("强风") => "风",
                string w when w.Contains("晴") => "晴",
                string w when w.Contains("多云") || w.Contains("阴") => "多云",
                string w when w.Contains("热") || w.Contains("冷") => "温",
                _ => "未知"
            };
        }




        static void SetTemperatureColor(int temp)
        {
            Console.ForegroundColor = temp switch
            {
                > 35 => ConsoleColor.Red,
                > 25 => ConsoleColor.DarkYellow,
                < 0 => ConsoleColor.Blue,
                _ => ConsoleColor.Green
            };
        }

        static void SetHumidityColor(int humidity)
        {
            Console.ForegroundColor = humidity switch
            {
                > 80 => ConsoleColor.DarkBlue,
                < 20 => ConsoleColor.DarkYellow,
                _ => ConsoleColor.DarkCyan
            };
        }

        static string GenerateThermometer(int temp)
        {
            int scale = Math.Clamp(temp, -20, 50);
            int barLength = (scale + 20) / 5; // 每5℃一个单位

            return $@"
  ┌{new string('─', 12)}┐
  │{new string('█', barLength).PadRight(12)}│ {temp}℃
  └{new string('─', 12)}┘
温度计刻度：-20℃ ~ 50℃
";
        }

        static string GenerateHumidityBar(int humidity)
        {
            int barLength = humidity / 10;

            return $@"
  ╔{new string('═', 10)}╗
  ║{new string('█', barLength).PadRight(10)}║ {humidity}%
  ╚{new string('═', 10)}╝
湿度指示条：0% ~ 100%
";
        }

    }
}
